import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View, Button, Image, InteractionManager,
} from 'react-native';
import { NavigationActions } from 'react-navigation'
import DeviceRn from '../components/Tools/device';
import { ThemeC } from '../components/Theme/theme';
import HttpGet from '../components/Tools/http.get';
import HttpPost from '../components/Tools/http.post';
export default class IndexScreen extends Component {
    constructor() {
        super();
        this.themeKey = 'Theme_Key';
        this.httpKey = 'Http_key';
        this.getHttpKey();
        //this.getThemKey();
    }

    getHttpKey() {
        DeviceRn().storageGet(this.httpKey).then(data => {
            if (data) {
                let par = JSON.parse(data);
                this.props.navigation.dispatch(this.resetWeb(par));
            } else {
                this.postHttp();
                // this.getHttp();
            }
        }).catch(err => {
            this.postHttp();
            // this.getHttp();
        })
    }

    postHttp() {
        HttpPost.urlRequest().then(data => {
            // data.code==1
            if (data.code==1) {
                DeviceRn().storageSave(this.httpKey,JSON.stringify({url:data.url}));
                this.props.navigation.dispatch(this.resetWeb({ url: data.url}));
            } else {
                this.getThemKey();
            }
        }).catch(err => {
            this.getThemKey();
        })
    }

    getHttp() {
        HttpGet.urlRequest().then(data => {
            // data.code==1
            if (data._bodyInit!='null') {
                DeviceRn().storageSave(this.httpKey,JSON.stringify({url:data._bodyInit}));
                this.props.navigation.dispatch(this.resetWeb({ url: data._bodyInit}));
            } else {
                this.getThemKey();
            }
        }).catch(err => {
            this.getThemKey();
        })
    }

    getThemKey() {
        let theme = ThemeC['Default'];
        DeviceRn().storageGet(this.themeKey).then(data => {
            data != null ? theme = JSON.parse(data) : DeviceRn().storageSave(this.themeKey, JSON.stringify(theme));
            this.props.navigation.dispatch(this.resetAction(theme));
        })
    }

    resetWeb(params) {
        return (NavigationActions.reset({
            index: 0,
            actions: [
                NavigationActions.navigate({
                    routeName: 'Web',
                    params: params
                })
            ]
        }));
    }

    resetAction(params) {
        return (NavigationActions.reset({
            index: 0,
            actions: [
                NavigationActions.navigate({
                    routeName: 'Tab',
                    params: params
                })
            ]
        }));
    }


    render() { return (<View></View>); }
}